package com.kongzue.baseframeworkdemo.activity;

import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.media.MediaRecorder;
import android.service.autofill.FillEventHistory;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.kongzue.baseframework.BaseActivity;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.OnActivityPermissionCallBack;
import com.kongzue.baseframework.util.Permission;
import com.kongzue.baseframeworkdemo.R;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicMarkableReference;

@Layout(R.layout.activity_video_record)
public class MediaRecorderActivity extends BaseActivity implements SurfaceHolder.Callback {
    private Button button;
    private SurfaceView surfaceView;
    private MediaRecorder mediaRecorder;
    private Camera camera; //摄像头的一些配置


    @Override
    public void initViews() {

        //当前手机预览的页面
        surfaceView = findViewById(R.id.surface);
        //开始或结束按钮
        button = findViewById(R.id.btn_opt);
        surfaceView.getHolder().addCallback(this);
        // 打开摄像头并将展示方向旋转90度
        camera = Camera.open();
        camera.setDisplayOrientation(90);
        Camera.Parameters parameters = camera.getParameters();
//        获取到Camera的原始NV21数据
        parameters.setPreviewFormat(ImageFormat.NV21);
        camera.setParameters(parameters);
        parameters.setPreviewSize(1280,720);

    }

    @Override
    public void initDatas(JumpParameter parameter) {
        Permission.build().CAMERA().STORAGE().EXTERNAL_STORAGE().MICROPHONE().get(new OnActivityPermissionCallBack<MediaRecorderActivity>() {
            @Override
            public void onSuccess(MediaRecorderActivity activity, String[] permissions) {
                toast("请求成功");
            }

            @Override
            public void onFail(MediaRecorderActivity activity) {
                super.onFail(activity);
                toast("请求失败");
            }
        });
        //相机回调
        camera.setPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                toast("data");
            }
        });
    }

    @Override
    public void setEvents() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取按钮文本内容
                String s = button.getText().toString();
                if(s.equals("开始")){
                    //点击了开始则设置按钮文本值为结束
                    button.setText("结束");
                    /**
                     * 开始录制
                     */
                    //1.创建recorder对象
                    mediaRecorder = new MediaRecorder();
                    //2.设置录制视频的方向
                    camera = Camera.open();//摄像头对象
                    camera.setDisplayOrientation(90);//将摄像头预览的角度进行调整
                    camera.unlock();
                    mediaRecorder.setCamera(camera);

                    //3.设置音频源（MIC：麦克风采集音频）
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    //4.设置视频源（CAMERA：摄像头采集视频）
                    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                    //5.设置视频输出格式（MP4）
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                    //6.设置音频编码格式
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    //7.设置视频编码格式
                    mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
                    //8.设置视频播放的方向
                    mediaRecorder.setOrientationHint(90);
                    //9.设置输出文件的位置
                    toast(getExternalFilesDir(""));
                    mediaRecorder.setOutputFile(new File(getExternalFilesDir(""),"a.mp4")
                            .getAbsolutePath());
                    //10.设置输出视频的大小
                    mediaRecorder.setVideoSize(1920,1080);
                    //11.设置视频的帧率
                    mediaRecorder.setVideoFrameRate(60);
                    //12.设置预览界面（设置一个Surface，也就是预览的页面，然后交给）
                    mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
                    try {
                        //13.准备录制
                        mediaRecorder.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //14.开始录制
                    mediaRecorder.start();

                }else{
                    //点击了结束则设置按钮文本值为开始
                    button.setText("开始");
                    //1.结束录制
                    mediaRecorder.stop();
                    //2.释放recorder对象
                    mediaRecorder.release();
                    //3.关闭摄像头
                    camera.stopPreview();
                    //4.释放
                    camera.release();
                }
            }
        });
    }


    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        log("surfaceChanged");
        System.out.println("surfaceChanged");

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }
}
